layui.use(['form','layer','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        //$ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        roleId = 0;

    function zTreeOnClick(event, treeId, treeNode) {
        table.reload('sysMenuListTable', {
            where: { //设定异步数据接口的额外参数，任意设
                "pId":treeNode.id
            }
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        }); //只重载数据
    };

    var setting = {
        view: {
            selectedMulti: false
        },
        callback: {
            onClick: zTreeOnClick
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: 0
            },
            key: {
                name: "deptName"
            }
        }
    }

    var setting1 = {
        view: {
            selectedMulti: false
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: 0
            },
            key: {
                name: "menuName"
            }
        }
    }

    getTreeData();

    function getTreeData(){
        $.ajax({
            type:"get",
            url:"http://localhost/admin/sysDept/getTreeList",
            dataType:"json",
            success:function(data){
                $.fn.zTree.init($("#tree"), setting, data.data);
                $.fn.zTree.getZTreeObj("tree").expandAll(true);
            }
        })
    }

    //用户列表
    var tableIns = table.render({
        elem: '#userList',
        url : 'http://localhost/admin/sysRole/getRoleList',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 20,
        id : "sysMenuListTable",
        cols : [[
            {field: 'roleName', title: '角色名称', width:180},
            {field: 'status', title: '状态', width:180, templet:function(d){
                    return d.status == '0'?'启用':'禁用';
                }},
            {title: '操作', minWidth:175, templet:'#userListBar',fixed:"right",align:"center"}
        ]]
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            table.reload("newsListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    function toAddOrUpdate(title, url){
        var index = layui.layer.open({
            title : title,
            type : 2,
            content : url,
            success : function(layero, index){
                setTimeout(function(){
                    layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }

    $(".add_btn").click(function(){
        toAddOrUpdate('添加', 'sysRoleAdd.html');
    })

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('userListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        }else{
            layer.msg("请选择需要删除的用户");
        }
    })

    //列表操作
    table.on('tool(userList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        roleId = data.id;
        if(layEvent === 'edit'){ //编辑
            toAddOrUpdate('修改', 'sysDeptUpdate.html?id='+data.id);
        }else if(layEvent === 'authrity'){
            //授权
            $.ajax({
                type:"get",
                url:"http://localhost/admin/sysMenu/getMenuByRoleId",
                data:{"roleId": roleId},
                dataType:"json",
                success:function(data){
                    $.fn.zTree.init($("#tree1"), setting1, data.data);
                    $.fn.zTree.getZTreeObj("tree1").expandAll(true);
                    showDeptMenuTree();
                }
            })
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除？',{icon:3, title:'提示信息'},function(index){
                // $.get("删除文章接口",{
                //     newsId : data.newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                    tableIns.reload();
                    layer.close(index);
                // })
            });
        }
    });

    function showDeptMenuTree(){
        layui.layer.open({
            type: 1,
            content: $('#deptMenuTree'),
            btn: ['确定', '取消'],
            area: ['400px', '600px'],
            yes: function(index, layero){
                var nodes = $.fn.zTree.getZTreeObj("tree1").getCheckedNodes(true);
                var ids = '';
                for (var i=0;i<nodes.length;i++){
                    ids += nodes[i].id + ",";
                }
                ids = ids.substring(0, ids.length-1);
                $.ajax({
                    type:"post",
                    url:"http://localhost/admin/sysMenu/insertRoleMenu",
                    data:{"deptId": roleId, "ids": ids},
                    dataType:"json",
                    success:function(data){
                        if(data.code == 0){
                            layui.layer.close(layui.layer.index)
                        }
                        layui.layer.msg(data.msg);
                    }
                })

            },
            btn2: function(index, layero){
                //按钮【按钮二】的回调
                //return false 开启该代码可禁止点击该按钮关闭
            }
        });
    }
})
